//The MIT License
//
//Copyright (c) 2009 nodchip
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in
//all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//THE SOFTWARE.
package tv.dyndns.kishibe.client.game;

import java.util.HashMap;
import java.util.Map;

import tv.dyndns.kishibe.client.Constant;
import tv.dyndns.kishibe.client.Sanitize;
import tv.dyndns.kishibe.client.SoundPlayer;
import tv.dyndns.kishibe.client.packet.PacketProblemData;
import tv.dyndns.kishibe.client.ui.Canvas;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.http.client.URL;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;

public class WidgetInputSenmusubi extends WidgetInputBase implements ClickHandler {
	private static final String BUTTON_SENMUSUBI = "gwt-Button-senmusubi";
	private static final String BUTTON_SENMUSUBI_SELECTED = "gwt-Button-senmusubiSelected";
	private static final String BUTTON_SENMUSUBI_IMAGE = "gwt-Button-senmusubiImage";
	private static final String BUTTON_SENMUSUBI_IMAGE_SELECTED = "gwt-Button-senmusubiImageSelected";
	private static final int EMPTY = -1;
	private final Button[] buttonLeft;
	private final Button[] buttonRight;
	private final Map<Button, Integer> mapRow = new HashMap<Button, Integer>();
	private final Map<Button, Integer> mapCol = new HashMap<Button, Integer>();
	private final int select[];
	private final Canvas canvas = new Canvas();
	private final int numberOfChoice;
	private final WidgetAnswer widgetAnswer;
	private final PacketProblemData problemData;
	private int lastRow = EMPTY;
	private int lastCol = EMPTY;
	private static final int LINE_WIDTH = 3;
	private static final String LINE_COLOR = "ff0000";
	private final Button buttonOk = new Button("OK", this);
	private final boolean isImageChoice;
	private final boolean isImageAnswer;

	public WidgetInputSenmusubi(WidgetAnswer widgetAnswer, PacketProblemData problemData) {
		this.problemData = problemData;
		this.widgetAnswer = widgetAnswer;
		this.numberOfChoice = problemData.getNumberOfChoice();
		this.isImageChoice = problemData.imageChoice;
		this.isImageAnswer = problemData.imageAnswer;

		buttonLeft = new Button[numberOfChoice];
		buttonRight = new Button[numberOfChoice];
		select = new int[numberOfChoice];

		final HorizontalPanel panel = new HorizontalPanel();
		panel.setVerticalAlignment(ALIGN_MIDDLE);
		add(panel);

		for (int i = 0; i < numberOfChoice; ++i) {
			select[i] = EMPTY;
		}

		// 左側ボタン群
		if (problemData.imageChoice) {
			final Grid gridLeft = new Grid(numberOfChoice, 1);
			for (int i = 0; i < numberOfChoice; ++i) {
				final String choice = problemData.randomizedChoice[i];
				final String html = getLetter(ALPHA, i) + "<img src='" + URL.encode(choice) + "' width='120px' height='90px'/>";
				buttonLeft[i] = new Button(html, this);
				buttonLeft[i].setStyleName(BUTTON_SENMUSUBI_IMAGE);
				mapCol.put(buttonLeft[i], 0);
				mapRow.put(buttonLeft[i], i);
				gridLeft.setWidget(i, 0, buttonLeft[i]);
			}
			panel.add(gridLeft);
		} else {
			final Grid gridLeft = new Grid(numberOfChoice, 2);
			for (int i = 0; i < numberOfChoice; ++i) {
				final Label label = new Label(getLetter(ALPHA, i));
				label.addStyleDependentName("buttonIndexSmall");
				gridLeft.setWidget(i, 1, label);

				buttonLeft[i] = new Button(Sanitize.getInstance().htmlChoice(problemData.randomizedChoice[i]), this);
				buttonLeft[i].setStyleName(BUTTON_SENMUSUBI);
				mapCol.put(buttonLeft[i], 0);
				mapRow.put(buttonLeft[i], i);
				gridLeft.setWidget(i, 0, buttonLeft[i]);
			}
			panel.add(gridLeft);
		}

		// 線を表示する部分
		int canvasWidth = 40;
		if (problemData.imageAnswer) {
			canvasWidth += 40;
		}
		if (problemData.imageChoice) {
			canvasWidth += 40;
		}
		int canvasHeight = (problemData.imageAnswer || problemData.imageChoice) ? 360 : 200;
		canvas.setPixelSize(canvasWidth, canvasHeight);
		panel.add(canvas);

		// 右側ボタン群
		if (problemData.imageAnswer) {
			final Grid gridRight = new Grid(numberOfChoice, 1);
			for (int i = 0; i < numberOfChoice; ++i) {
				final String answer = problemData.randomizedAnswer[i];
				final String html = getLetter(DIGIT, i) + "<img src='" + URL.encode(answer) + "' width='120px' height='90px'/>";
				buttonRight[i] = new Button(html, this);
				buttonRight[i].setStyleName(BUTTON_SENMUSUBI_IMAGE);
				mapCol.put(buttonRight[i], 1);
				mapRow.put(buttonRight[i], i);
				gridRight.setWidget(i, 0, buttonRight[i]);
			}
			panel.add(gridRight);
		} else {
			final Grid gridRight = new Grid(numberOfChoice, 2);
			for (int i = 0; i < numberOfChoice; ++i) {
				final Label label = new Label(getLetter(DIGIT, i));
				label.addStyleDependentName("buttonIndexSmall");
				gridRight.setWidget(i, 0, label);

				buttonRight[i] = new Button(Sanitize.getInstance().htmlChoice(problemData.randomizedAnswer[i]), this);
				buttonRight[i].setStyleName(BUTTON_SENMUSUBI);
				mapCol.put(buttonRight[i], 1);
				mapRow.put(buttonRight[i], i);
				gridRight.setWidget(i, 1, buttonRight[i]);
			}
			panel.add(gridRight);
		}

		// OKボタン
		buttonOk.setStyleName("gwt-Button-senmusubiControl");
		add(buttonOk);
	}

	public void enable(boolean b) {
		for (int i = 0; i < numberOfChoice; ++i) {
			buttonLeft[i].setEnabled(b);
			buttonRight[i].setEnabled(b);
		}
		buttonOk.setEnabled(b);
	}

	private void updateLine() {
		canvas.prepare();

		// final int offsetCanvasX = 0;
		// final int offsetCanvasY = 0;
		final int offsetCanvasX = canvas.getAbsoluteLeft();
		final int offsetCanvasY = canvas.getAbsoluteTop();

		for (int i = 0; i < numberOfChoice; ++i) {
			if (select[i] == EMPTY) {
				continue;
			}

			final Button left = buttonLeft[i];
			final Button right = buttonRight[select[i]];

			final int leftX = left.getAbsoluteLeft() + left.getOffsetWidth() - offsetCanvasX;
			final int leftY = left.getAbsoluteTop() + left.getOffsetHeight() / 2 - offsetCanvasY;
			final int rightX = right.getAbsoluteLeft() - offsetCanvasX;
			final int rightY = right.getAbsoluteTop() + right.getOffsetHeight() / 2 - offsetCanvasY;

			canvas.drawLine(leftX, leftY, rightX, rightY, LINE_WIDTH, LINE_COLOR);
		}

		canvas.present();
	}

	@Override
	public void onClick(ClickEvent event) {
		final Object sender = event.getSource();
		if (sender == buttonOk) {
			sendAnswer("");
			return;
		}

		{
			final String styleNameLeft = isImageChoice ? BUTTON_SENMUSUBI_IMAGE : BUTTON_SENMUSUBI;
			final String styleNameRight = isImageAnswer ? BUTTON_SENMUSUBI_IMAGE : BUTTON_SENMUSUBI;
			for (int i = 0; i < numberOfChoice; ++i) {
				buttonLeft[i].setStyleName(styleNameLeft);
				buttonRight[i].setStyleName(styleNameRight);
			}
		}

		final int row = ((Integer) mapRow.get(sender)).intValue();
		final int col = ((Integer) mapCol.get(sender)).intValue();

		if (lastRow == EMPTY || lastCol == col) {
			// 同じ列がクリックされた or 初めてのクリック
			lastRow = row;
			lastCol = col;
			if (col == 0) {
				final String styleNameLeft = isImageChoice ? BUTTON_SENMUSUBI_IMAGE_SELECTED : BUTTON_SENMUSUBI_SELECTED;
				buttonLeft[row].setStyleName(styleNameLeft);
			} else {
				final String styleNameRight = isImageChoice ? BUTTON_SENMUSUBI_IMAGE_SELECTED : BUTTON_SENMUSUBI_SELECTED;
				buttonRight[row].setStyleName(styleNameRight);
			}

		} else {
			// 違う列がクリックされた

			final int left, right;
			if (col == 0) {
				// 最後は左がクリックされた
				left = row;
				right = lastRow;
			} else {
				// 最後は右がクリックされた
				left = lastRow;
				right = row;
			}

			for (int i = 0; i < numberOfChoice; ++i) {
				// 左→右リンク修正
				if (select[i] == right) {
					select[i] = EMPTY;
				}
			}
			select[left] = right;

			lastRow = EMPTY;
			lastCol = EMPTY;
		}

		updateLine();

		for (int i = 0; i < numberOfChoice; ++i) {
			if (select[i] == EMPTY) {
				SoundPlayer.getInstance().play(Constant.SOUND_URL_BUTTON_PUSH);
				return;
			}
		}

		// 回答送信
		final StringBuffer answerSend = new StringBuffer();
		final StringBuffer answerDisplay = new StringBuffer();
		for (int i = 0; i < numberOfChoice; ++i) {
			if (i != 0) {
				answerSend.append(Constant.DELIMITER_GENERAL);
			}
			answerSend.append(problemData.randomizedChoice[i]);
			answerSend.append(Constant.DELIMITER_KUMIAWASE_PAIR);
			answerSend.append(problemData.randomizedAnswer[select[i]]);

			final int index = select[i];
			answerDisplay.append(getLetter(DIGIT, index));
		}
		sendAnswer(answerSend.toString());
		widgetAnswer.setText(answerDisplay.toString());
	}
}
